﻿using CoreDomain;
using DomainService.IService.OverallAuth;
using Model;
using Model.BusinessModel.OutPut;
using Model.OverallAtuhModel;
using System.Collections.Generic;
using Utility;
using Utility.Enum;

namespace DomainService.Service.OverallAuth
{
    /// <summary>
    /// OverallAuth系统接口实现
    /// </summary>
    public class OverallAuthApiService : IOverallAuthApiService
    {
        #region 构造实例化

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="formRepository"></param>
        public OverallAuthApiService()
        {
        }

        #endregion

        #region  公司相关

        /// <summary>
        /// 获取公司接口
        /// </summary>
        /// <returns></returns>
        public ReceiveStatus<List<SelectOutPut>> GetCorporation()
        {
            ReceiveStatus<List<SelectOutPut>> receiveStatus = new ReceiveStatus<List<SelectOutPut>>();
            try
            {
                //post请求
                var data = HttpRequest.GetAsync<List<SelectOutPut>>("api/OpenApi/GetCorporation").Result;
                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SelectOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        #endregion

        #region  菜单相关

        /// <summary>
        /// 获取用户所属菜单
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="corporationKey">公司key</param>
        /// <param name="systemKey">系统key</param>
        /// <returns>返回用户所属菜单</returns>
        public ReceiveStatus<List<SysMenuOutPut>> GetMenuByUserId(LoginOutPut loginOutPut)
        {
            ReceiveStatus<List<SysMenuOutPut>> receiveStatus = new ReceiveStatus<List<SysMenuOutPut>>();

            try
            {
                //post请求
                var data = HttpRequest.PostAsync<List<SysMenuOutPut>>("api/OpenApi/GetUserSystemMenu", loginOutPut, loginOutPut.Token).Result;

                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SysMenuOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        #endregion

        #region 按钮相关

        /// <summary>
        /// 获取菜单按钮权限
        /// </summary>
        /// <param name="menuId">菜单key</param>
        /// <param name="buttonRoleType">按钮类型</param>
        /// <param name="loginOutPut">登录信息</param>
        /// <returns></returns>
        public ReceiveStatus<List<SysButtonDataOutPut>> GetMenuButtonAuthList(string menuId, int buttonRoleType, LoginOutPut loginOutPut)
        {
            ReceiveStatus<List<SysButtonDataOutPut>> receiveStatus = new();
            try
            {
                string url = string.Format("api/SysButton/GetMenuButtonAuthList?menuId={0}&buttonRoleType={1}&systemKey={2}", menuId, buttonRoleType,loginOutPut.SystemKey);
                var data = HttpRequest.GetAsync<List<SysButtonDataOutPut>>(url, loginOutPut.Token).Result;
                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SysButtonDataOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        /// <summary>
        /// 获取数据按钮权限
        /// </summary>
        /// <param name="input">匹配模型</param>
        /// <param name="loginOutPut">登录信息</param>
        /// <returns></returns>
        public ReceiveStatus<List<SysButtonDataOutPut>> GetMenuDataButtonAuth(MatchingDataButtonAuthInput input, LoginOutPut loginOutPut)
        {
            ReceiveStatus<List<SysButtonDataOutPut>> receiveStatus = new();
            try
            {
                string url = string.Format("api/MatchFormula/GetMenuDataButtonAuth");
                var data = HttpRequest.PostAsync<List<SysButtonDataOutPut>>(url, input, loginOutPut.Token).Result;
                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SysButtonDataOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        /// <summary>
        /// 获取按钮
        /// </summary>
        /// <param name="menuId">菜单key</param>
        /// <param name="buttonRoleType">按钮类型</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public ReceiveStatus<List<SysButtonDataOutPut>> GetMenuButtonList(string menuId, int buttonRoleType, string token)
        {
            ReceiveStatus<List<SysButtonDataOutPut>> receiveStatus = new();
            try
            {
                string url = string.Format("api/SysButton/GetMenuButtonList?menuId={0}&buttonRoleType={1}", menuId, buttonRoleType);
                var data = HttpRequest.GetAsync<List<SysButtonDataOutPut>>(url, token).Result;
                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SysButtonDataOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        #endregion

        #region 用户相关

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginModel">登录模型</param>
        /// <returns></returns>
        public ReceiveStatus<List<LoginOutPut>> Login(LoginInput loginModel)
        {
            ReceiveStatus<List<LoginOutPut>> receiveStatus = new ReceiveStatus<List<LoginOutPut>>();
            try
            {
                var data = HttpRequest.PostLoginAsync<List<LoginOutPut>>("api/SSOAuthCenter/Login", loginModel).Result;
                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<LoginOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        /// <summary>
        /// 根据公司获取人员
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public ReceiveStatus<List<SelectOutPut>> GetUserByCorporationKey(string corporationKey)
        {
            ReceiveStatus<List<SelectOutPut>> receiveStatus = new ReceiveStatus<List<SelectOutPut>>();
            try
            {
                var url = string.Format("api/SysUser/GetUserByCorporationKey?corporationKey={0}", corporationKey);
                var data = HttpRequest.GetAsync<List<SelectOutPut>>(url).Result;

                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SelectOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        /// <summary>
        /// 根据公司获取所有用户
        /// 构建用户缓存
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public ReceiveStatus<List<SysUser>> GetAllUserByCorporationKey(string corporationKey)
        {
            ReceiveStatus<List<SysUser>> receiveStatus = new();
            try
            {

                var url = string.Format("api/SysUser/GetAllUser?corporationKey={0}", corporationKey);
                var apiResult = HttpRequest.GetAsync<List<SysUser>>(url).Result;

                if (!apiResult.Success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("获取用户数据接口报错：{0}", apiResult.Message);
                }

                var cacheResult = MemoryCacheHelper.AddCache(ConstHelper.UserCacheKey, apiResult?.Data ?? new List<SysUser>(), 1440);
                if (!cacheResult.success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("缓存用户数据出错：{0}", cacheResult.msg);
                }
                receiveStatus.data = apiResult?.Data ?? new List<SysUser>();
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper.CustomException(ex.Message);
            }
            return receiveStatus;
        }

        #endregion

        #region 部门相关

        /// <summary>
        /// 根据公司获取所有部门数据
        /// 构建部门缓存
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public ReceiveStatus<List<SysDepartment>> GetAllDepartmentByCorporationKey(string corporationKey)
        {
            ReceiveStatus<List<SysDepartment>> receiveStatus = new();
            try
            {
                var url = string.Format("api/SysDepartment/GetAllDepartment?corporationKey={0}", corporationKey);
                var apiResult = HttpRequest.GetAsync<List<SysDepartment>>(url).Result;

                if (!apiResult.Success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("获取部门数据接口报错：{0}", apiResult.Message);
                }

                var cacheResult = MemoryCacheHelper.AddCache(ConstHelper.DepartmentCacheKey, apiResult?.Data ?? new List<SysDepartment>(), 1440);
                if (!cacheResult.success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("缓存部门数据出错：{0}", cacheResult.msg);
                }
                receiveStatus.data = apiResult?.Data ?? new List<SysDepartment>();
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper.CustomException(ex.Message);
            }

            return receiveStatus;

        }

        /// <summary>
        /// 根据公司获取所有部门数据--树形结构
        /// 构建部门树缓存
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public ReceiveStatus<List<TreeOutPut>> GetDepartmentTree(string corporationKey)
        {
            ReceiveStatus<List<TreeOutPut>> receiveStatus = new();
            try
            {
                var url = string.Format("api/SysDepartment/GetCorporationDepartmentList?corporationKey={0}", corporationKey);
                var apiResult = HttpRequest.GetAsync<List<TreeOutPut>>(url).Result;

                if (!apiResult.Success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("获取部门树数据接口报错：{0}", apiResult.Message);
                }

                var cacheResult = MemoryCacheHelper.AddCache(ConstHelper.DepartmentTreeCacheKey, apiResult?.Data ?? new List<TreeOutPut>(), 1440);
                if (!cacheResult.success)
                {
                    receiveStatus.success = false;
                    receiveStatus.code = CodeStatuEnum.Error;
                    receiveStatus.msg = string.Format("缓存部门树数据出错：{0}", cacheResult.msg);
                }
                receiveStatus.data = apiResult?.Data ?? new List<TreeOutPut>();
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper.CustomException(ex.Message);
            }

            return receiveStatus;

        }

        /// <summary>
        /// 获取部门下的人员
        /// </summary>
        /// <param name="corporationKey">公司key</param>
        /// <returns></returns>
        public ReceiveStatus<List<TreeOutPut>> GetDepartmentUser(string corporationKey)
        {
            ReceiveStatus<List<TreeOutPut>> receiveStatus = new ReceiveStatus<List<TreeOutPut>>();
            if (string.IsNullOrWhiteSpace(corporationKey))
                return ExceptionHelper<List<TreeOutPut>>.CustomExceptionData("不存在公司信息!");

            //获取部门
            var depList = MemoryCacheHelper.GetCachedDataByKey<List<TreeOutPut>>(ConstHelper.DepartmentTreeCacheKey);
            if (depList.success == false)
                ExceptionHelper.ThrowBusinessException("部门缓存不存在或已过期,请重置缓存");

            //获取用户
            var userList = MemoryCacheHelper.GetCachedDataByKey<List<SysUser>>(ConstHelper.UserCacheKey);
            if (userList.success == false)
                ExceptionHelper.ThrowBusinessException("用户缓存不存在或已过期,请重置缓存");

            var departmentList = JsonHelper.DeepCopy(depList);
            //把流程数据添加到节点上
            if (!departmentList.success)
            {
                return ExceptionHelper<List<TreeOutPut>>.CustomExceptionData("部门信息查询失败!");
            }
            if (departmentList.data == null || departmentList.data.Count == 0)
            {
                return ExceptionHelper<List<TreeOutPut>>.CustomExceptionData("不存在部门信息!");
            }
            if (userList.data?.Count > 0)
            {
                foreach (var item in userList.data)
                {
                    var treeNode = new TreeOutPut()
                    {
                        key = item.UserId,
                        pKey = item.DepartmentId,
                        label = item.UserName,
                        isLeaf = true,
                        nodeType = (int)TreeNodeTypeEnum.User,
                        children = new List<TreeOutPut>()
                    };
                    TreeCore.AddTreeNode(departmentList.data, treeNode);
                }
            }
            receiveStatus.data = departmentList.data;

            return receiveStatus;
        }

        #endregion

        #region 数据列

        /// <summary>
        /// 根据菜单id获取列，用于数据列权限
        /// </summary>
        /// <param name="menuId">菜单id</param>
        /// <returns></returns>
        public ReceiveStatus<List<SysMenuTableColsOutPut>> GetTableColsByMenuId(string menuId)
        {
            ReceiveStatus<List<SysMenuTableColsOutPut>> receiveStatus = new ReceiveStatus<List<SysMenuTableColsOutPut>>();
            try
            {
                var url = string.Format("api/SysMenuTableCols/GetTableColsByMenuId?menuId={0}", menuId);
                var data = HttpRequest.GetAsync<List<SysMenuTableColsOutPut>>(url).Result;

                receiveStatus.data = data.Data;
            }
            catch (Exception ex)
            {
                receiveStatus.success = false;
                receiveStatus.code = Utility.Enum.CodeStatuEnum.Error;
                receiveStatus.msg = ex.Message;
                ExceptionHelper<List<SysMenuTableColsOutPut>>.CustomExceptionData(ex.Message);
            }

            return receiveStatus;
        }

        /// <summary>
        /// 同步数据列
        /// </summary>
        /// <param name="loginOutPut">登录人员信息</param>
        /// <returns></returns>
        public ReceiveStatus SynchronousCols(LoginOutPut loginOutPut)
        {
            var receiveStatus = DataColsCore.SynchronousCols(loginOutPut);
            return receiveStatus;
        }

        #endregion
    }
}
